package com.tony.Util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class OkHttpUtil {
    static OkHttpClient client = new OkHttpClient();
    public static String get(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()){
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    public static String form(String url, Map<String,String> param) throws IOException {
        FormBody.Builder builder =new FormBody.Builder();
        for(String key:param.keySet()){
            builder.add(key,param.get(key));
        }
        FormBody body  = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()){
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }


    public static void main(String[] args) throws IOException {
        System.out.println(get("http://localhost:8010/getinfo?name=tony&age=22"));
        System.out.println("####################");
        Map<String,String> map = new HashMap<>();
        map.put("name","test");
        map.put("age","21");

        System.out.println(form("http://localhost:8010/postinfo", map));
    }
}
